module MEM_WB(
    input wire we,
    input wire clk,
    input wire reset,
    input wire is_write_reg_in,//if the instrcution write the register
    input wire res_from_mem_in,//result source
    input wire [4:0] dest_in,
    input wire [31:0] pc_in,
    input wire [31:0] alu_result_in,
    input wire [31:0] mem_result_in,
//csr
    input wire is_write_csr_in,
    input wire [13:0]csr_dest_in,
    input wire [31:0]csr_wdata_in,
    input wire [31:0]csr_rdata_in,
    input wire res_from_csr_in,

    output reg is_write_reg,//if the instrcution write the register
    output reg [4:0] dest,
    output reg [31:0] pc,
    output reg [31:0] wb_data,
//csr
    output reg is_write_csr,
    output reg [13:0]csr_dest,
    output reg [31:0]csr_wdata,

    input wire exc_in,
    input wire [5:0] ecode_in,
    input wire esubcode_in,
    input wire [31:0] badv_in,

    output reg exc,
    output reg [6:0]exc_entry,
    output reg [31:0] badv
    );
    assign MEM_WB_READY=1;
    always@(posedge clk)begin
        if(reset)begin
            is_write_reg<=0;
            dest<=0;
            pc<=0;
            wb_data<=0;
            is_write_csr<=0;
            csr_dest<=0;
            csr_wdata<=0;
            exc<=0;
            exc_entry<=0;
            badv<=0;
        end
        else if(we)begin
            is_write_reg<=is_write_reg_in & ~exc_in;
            dest<=dest_in;
            pc<=pc_in;
            wb_data<=res_from_csr_in ? csr_rdata_in : res_from_mem_in ? mem_result_in : alu_result_in;
            is_write_csr<=is_write_csr_in & ~exc_in;
            csr_dest<=csr_dest_in;
            csr_wdata<=csr_wdata_in;
            exc<=exc_in;
            exc_entry<={esubcode_in,ecode_in};
            badv<=badv_in;
        end
    end
endmodule
